package com.yuanian.wf.pojo.model;

import com.yuanian.wf.annotation.ProcessAction;
import com.yuanian.wf.event.process.EndProcessAfterEvent;
import com.yuanian.wf.event.process.EndProcessBeforeEvent;
import com.yuanian.wf.event.process.StartProcessAfterEvent;
import com.yuanian.wf.event.process.StartProcessBeforeEvent;
import com.yuanian.wf.event.task.CompleteTaskAfterEvent;
import com.yuanian.wf.event.task.CompleteTaskBeforeEvent;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * WfProcessKey注解对应的管理类
 */
public class ProcessKey {

    private String processKey;
    private Map<String, com.yuanian.wf.pojo.model.ProcessAction> processActionMap;
    private Class clz;

    public ProcessKey(String processKey, Class clz) {
        this.processKey = processKey;
        this.processActionMap = new HashMap<>();
        //获取类上方法
        Method[] methods = clz.getDeclaredMethods();
        for (Method method : methods) {
            //方法上是否存在WfProcessAction
            if (method.isAnnotationPresent(ProcessAction.class)) {
                ProcessAction processAction = method.getAnnotation(ProcessAction.class);
                //获取方法上的参数类型
                Class[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1) {
                    Class parameterType = parameterTypes[0];
                    if (parameterType == StartProcessBeforeEvent.class || parameterType == StartProcessAfterEvent.class || parameterType == EndProcessBeforeEvent.class || parameterType == EndProcessAfterEvent.class) {
                        addProcessAction(parameterType.getSimpleName(), new com.yuanian.wf.pojo.model.ProcessAction(parameterType, processAction.async(), null, this, method));
                    } else if (parameterType == CompleteTaskBeforeEvent.class || parameterType == CompleteTaskAfterEvent.class) {
                        addProcessAction(parameterType.getSimpleName() + "$" + processAction.taskKey(), new com.yuanian.wf.pojo.model.ProcessAction(parameterType, processAction.async(), processAction.taskKey(), this, method));
                    }
                }
            }
        }
    }

    public void addProcessAction(String id, com.yuanian.wf.pojo.model.ProcessAction processAction) {
        processActionMap.put(id, processAction);
    }

    public com.yuanian.wf.pojo.model.ProcessAction getProcessAction(String id) {
        return processActionMap.get(id);
    }

}
